var QQMapWX = require('./qqmap-wx-jssdk');
var qqmapsdk = new QQMapWX({
  key: 'PTBBZ-KL6KC-MNM25-A5DJY-Y3YVT-XTBGL' // 必填
});
//时间格式 年-月-日 小时:分钟:秒钟
const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return `${[year, month, day].map(formatNumber).join('-')} ${[hour, minute, second].map(formatNumber).join(':')}`
}
//时间格式：月/日
const todayTiem = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return `${[month, day].map(formatNumber).join('/')}`
}

//时间字符串拆分 年-月-日 拆分成 月/日
const tiemString = (data) => {
  let stringData = data.split('-')[1] + '/' + data.split('-')[2]
  return stringData
}

//时间段数据返回
const timeState = (activityFlag, activityTime, nowTime) => {
  let countMap = []
  let temp = activityTime
  let list = {}
  if (activityFlag !== 1) {
    for (let j = 0; j < temp.length; j++) {
      countMap.push({
        startTime: temp[j][0],
        endTime: temp[j][1]
      })
    }
    list.temp = activityTime.map(x => activityFlag)
    list.countMap = countMap
    return list
  }
  // 循环判断时间段
  for (let i = 0; i < temp.length; i++) {
    countMap.push({
      startTime: temp[i][0],
      endTime: temp[i][1]
    })
    if (temp[i][0] < nowTime) {
      if (temp[i][1] > nowTime) {
        temp[i] = 1
      } else {
        temp[i] = 0
      }
    } else {
      temp[i] = 2
    }
  }
  list.temp = temp
  list.countMap = countMap
  // 返回每个时段的标识 0 已经结束   1 进行中  2 未开始
  return list
}

//当前定位数据
const locationData = () => {
  console.log(111)
  return new Promise((resolve, reject) => {
  let locationInfo = {}
  let locationVal = ''
  wx.getLocation({
    type: 'gcj02',
    success(res) {
      locationVal = res.latitude + ',' + res.longitude
      qqmapsdk.reverseGeocoder({
        location: locationVal,
        success: function (res) {
          console.log(1)
          locationInfo = res.result
          wx.setStorageSync('locationInfo', res.result)
          wx.setStorageSync('currentDate', new Date().getHours())
          resolve(res)
        }
      })
      
    },fail(err){
      console.log(err)
      /*
      wx.getSetting({
        success: function (res) {
         var statu = res.authSetting;
         if (!statu['scope.userLocation']) {
          wx.showModal({
           title: '是否授权当前位置',
           content: '需要获取您的地理位置，请确认授权，否则地域功能将无法使用',
           showCancel:false,
           success: function (tip) {
            if (tip.confirm) {
             wx.openSetting({
              success: function (data) {
               if (data.authSetting["scope.userLocation"] === true) {
                wx.showToast({
                 title: '授权成功',
                 icon: 'success',
                 duration: 1000
                })
                //授权成功之后，再调用
                locationData()
               } else {
                wx.showToast({
                 title: '授权失败',
                 icon: 'success',
                 duration: 1000
                })
                locationData()

               }
              
              }
             })
            }
           }
          })
         }
        },
        fail: function (res) {
         wx.showToast({
          title: '调用授权窗口失败',
          icon: 'success',
          duration: 1000
         })
        }
       })
       */
      reject(err)
    }
  })

})

}

//通过地址解析
const reverseLocationData = (data) => {
  let location=""
  // 调用接口
  qqmapsdk.search({
    keyword: data,
    success: function (res) {
      console.log(res)
      location=res.data[0].location.lat+','+res.data[0].location.lng
      wx.setStorageSync('reverseLocationData', res.data[0].location.lat+','+res.data[0].location.lng)
    },
    fail: function (res) {
      // console.log(res);
    },
    complete: function (res) {
      // console.log(res);
    }
  });
}

//时间 --- 年/月/日
const formatDate = (date) => {
  var year = date.getFullYear();
  var month = date.getMonth() + 1;
  var day = date.getDate();
  var hour = date.getHours();
  var minute = date.getMinutes();
  var second = date.getSeconds();
  return year + "-" + month + "-" + day
}

//时间 --- 年,月,日
const formatGetDate = (date) => {
  var year = date.getFullYear();
  var month = date.getMonth() + 1;
  var day = date.getDate();
  var hour = date.getHours();
  var minute = date.getMinutes();
  var second = date.getSeconds();
  return {
    year: year,
    month: month,
    day: day
  }
}

//时间 --- 月份天数
const formatDateDays = (date) => {
  var year = date.getFullYear();
  var month = date.getMonth() + 1;
  var mm = new Date(year, month, 0).getDate()
  return mm
}


//时间字符串拼接--- xxxx年xx月xx日
const formatDateSplicing = (date) => {
  var frontData = date.split(' ')[0]
  var completeData = frontData.split('-')[0] + '年' + frontData.split('-')[1] + '月' + frontData.split('-')[2] + '日'
  return completeData
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}

//计算右侧胶囊位置
const capsuleData = () => {
  let infoData = {}
  // 1.获取屏幕可使用宽度
  let windowWidth = wx.getSystemInfoSync().windowWidth;
  // 2.获取状态栏高度
  const statusBarHeight = wx.getSystemInfoSync().statusBarHeight;
  // // 3.获取胶囊按钮位置信息
  const menuButton = wx.getMenuButtonBoundingClientRect();
  // 4.计算出导航栏高度  换算成rpx
  let navHeight = (menuButton.height + (menuButton.top - statusBarHeight) * 2) * (750 / windowWidth);
  // // 5.导航栏与状态栏拉开距离  margin-top: statusBarTop + 'rpx'; 
  let statusBarTop = statusBarHeight * (750 / windowWidth);
  infoData.height = navHeight
  infoData.marginTop = statusBarTop
  return infoData
}

//提示弹窗
const tip = (content,type) =>{
  wx.showModal({
    title: '提示',
    content: content,
    success (res) {
      if (res.confirm) {
        console.log('用户点击确定')
        if(type==1){
          wx.navigateBack({
            delta: 1
          })
        }
      } else if (res.cancel) {
        console.log('用户点击取消')
      }
    }
  })
}
//版本比对
const compareVersion=function(v1, v2) {
  v1 = v1.split('.')
  v2 = v2.split('.')
  const len = Math.max(v1.length, v2.length)

  while (v1.length < len) {
    v1.push('0')
  }
  while (v2.length < len) {
    v2.push('0')
  }

  for (let i = 0; i < len; i++) {
    const num1 = parseInt(v1[i])
    const num2 = parseInt(v2[i])

    if (num1 > num2) {
      return 1
    } else if (num1 < num2) {
      return -1
    }
  }

  return 0
}

// 时分秒
const timeStampToHms = (seconds) => {
  var h,m,s
  h = parseInt(seconds/3600)
  h = h > 9 ? h : '0' + h
  m = parseInt(seconds%3600/60)
  m = m > 9 ? m : '0' + m
  s = parseInt(seconds%60)
  s = s > 9 ? s : '0' + s
  //console.log(m,s)
  //return [h, m, s].join(':')
  return m+':'+s
}


module.exports = {
  formatTime,
  todayTiem,
  timeState,
  tiemString,
  locationData,
  formatDate,
  formatGetDate,
  formatDateDays,
  formatDateSplicing,
  capsuleData,
  reverseLocationData,
  tip,
  compareVersion,
  timeStampToHms
}